from django.db.models import Q
from django.views import View
from django.http.response import JsonResponse
from user.models import User, Role
from .models import ReasonType, Leave, ExamineLeave
from datetime import datetime
from django.utils.decorators import method_decorator
import json
from zhineng.models import Classes, College
import redis
from django_system.role_recognize import check_permission

r = redis.Redis(host='120.25.166.156', port=6379, password='040908Gds.', decode_responses=True, db=6)


class GetLeaveNeed(View):
    """
    获取不同请假身份请假时所需要的请假类型，
    post：提交假条
    """

    @method_decorator(check_permission(['老师', '班主任', '学生']))
    def get(self, request):
        username = request.user
        user = User.objects.filter(username=username).first()
        if '学生' in [i.name for i in user.roles.all()]:
            reason_list = list(ReasonType.objects.filter(is_stu_ask=True).all().values())
        else:
            reason_list = list(ReasonType.objects.all().values())
        return JsonResponse({'msg': 'OK', 'reason_list': reason_list, 'code': 200})

    @method_decorator(check_permission(['老师', '班主任', '学生']))
    def post(self, request):
        data = json.loads(request.body)
        reason_id = data['reason_type']
        username = request.user
        user = User.objects.filter(username=username).first()
        try:
            leave_ = Leave.objects.filter(
                Q(ask_user=user) & Q(status='审核中')).first()
            if leave_:
                return JsonResponse({'msg': '您已经提交过请假申请，请耐心等待审核', 'code': 401})
        except:
            pass
        start_time = data['start_time']
        end_time = data['end_time']
        description = data['description']
        reason = ReasonType.objects.filter(id=reason_id).first()
        leave = Leave.objects.create(ask_user=user, reason_type=reason, description=description, start_time=start_time,
                                     end_time=end_time)
        d1 = datetime.strptime(start_time, '%Y-%m-%d %H:%M:%S')
        d2 = datetime.strptime(end_time, '%Y-%m-%d %H:%M:%S')
        day = (d2 - d1).days
        self.get_need_user(leave, day, user)
        return JsonResponse({'msg': 'OK', 'code': 200})

    @staticmethod
    def get_need_user(leave, day, user):
        need_list = {}
        sort_list = ['班主任', '老师']
        user_all = user.classes_user.first().user.all()
        first_user = 0
        for i in user_all:
            if i.roles.filter(name='班主任').all().values('name'):
                need_list['c_teacher'] = i
                leave.examine_user.add(i)
                first_user = i.id
            if i.roles.filter(name='老师').all().values('name'):
                need_list['teacher'] = i
                leave.examine_user.add(i)
        dean = user.classes_user.first().colleges.college_dean
        rector = Role.objects.filter(name='校长').first().users.first()
        if day <= 1:
            return need_list
        elif 1 < day <= 3:
            need_list['dean'] = dean
            leave.examine_user.add(dean)
            sort_list.append('院长')
        else:
            need_list['dean'] = dean
            need_list['rector'] = rector
            leave.examine_user.add(dean)
            leave.examine_user.add(rector)
            sort_list.append('院长')
            sort_list.append('校长')
        r.set(leave.ask_user.id,
              json.dumps({'ask_user': leave.ask_user.id, 'receiver_user': first_user, 'list': sort_list}))
        body = {
            'next_user': need_list['teacher'].id,
            'ask_user': user.id,
            'message': f'用户{user.id}发起了请假，需要审核'
        }
        # send_msg_to_queue(str(need_list['c_teacher'].id), json.dumps(body))
        return need_list


class GetMyLeave(View):
    """
    学生获取个人假条信息
    """

    @method_decorator(check_permission(['老师', '班主任', '学生']))
    def get(self, request):
        username = request.user
        user_ = User.objects.filter(username=username).first()
        try:
            leave_list = Leave.objects.filter(ask_user=user_).all().values('description', 'start_time', 'end_time',
                                                                           'ask_time', 'status').order_by('-ask_time')
            return JsonResponse({'msg': 'OK', 'leave_list': list(leave_list), 'code': 200})
        except Exception as e:
            return JsonResponse({'msg': '暂无请假信息', 'code': 200})



class GetLeaveList(View):
    """
    获取请假列表
    """

    @method_decorator(check_permission(['老师', '校长', '班主任', '院长']))
    def get(self, request):
        username = request.user
        user_ = User.objects.filter(username=username).first()
        role = user_.roles.first().name
        user = User.objects.all()
        stu_list = []
        leaves = []
        for i in user:
            if i.roles.filter(name='学生').all().values('name'):
                if user_.classes_user.first() in i.classes_user.all():
                    stu_list.append(i)
        if role in ['老师', '班主任']:
            leaves = Leave.objects.filter(Q(ask_user__in=stu_list) & Q(status='审核中')).all().order_by('-ask_time')
        elif role == '院长':
            if Role.objects.get(name='院长') in user_.roles.all():
                college = College.objects.filter(college_dean=user_).first()
                classes = Classes.objects.filter(colleges=college).all()
                for i in classes:
                    for k in i.user.all():
                        if Role.objects.get(name='学生') in k.roles.all():
                            stu_list.append(k)
            leaves = Leave.objects.filter(Q(ask_user__in=stu_list) & Q(status='审核中')).all().order_by('-ask_time')
        elif role == '校长':
            leaves = Leave.objects.filter(status='审核中').all().order_by('-ask_time')
        leave_list = self.get_need_examine_leave_list(leaves, role)
        examine_list = []
        for i in leave_list:
            examine_list.append({'ask_user': i.ask_user.username, 'description': i.description, 'ask_time': i.ask_time,
                                 'start_time': i.start_time, 'end_time': i.end_time, 'leave_id': i.id})
        return JsonResponse({'msg': 'OK!!!', 'leave_list': examine_list, 'code': 200})

    @method_decorator(check_permission(['老师', '校长', '班主任', '院长']))
    def put(self, request):
        data = json.loads(request.body)
        leave_id = data['leave_id']
        user = User.objects.filter(username=request.user).first()
        leave = ExamineLeave.objects.filter(Q(user=user) & Q(leave_id=leave_id)).first()
        try:
            leave.is_agree = True
            leave.save()
            leave_list = Leave.objects.filter(id=leave_id).first().examine.all()
            agree_num = 0
            for i in leave_list:
                if i.is_agree:
                    agree_num += 1
            if agree_num == leave_list.count():
                Leave.objects.filter(id=leave_id).update(status='已通过')
            return JsonResponse({'msg': 'OK！！！！', 'code': 200})
        except Exception as e:
            return JsonResponse({'msg': f'审批失败原因是{e}', 'code': 200})

    @method_decorator(check_permission(['老师', '校长', '班主任', '院长']))
    def delete(self, request):
        data = json.loads(request.body)
        leave_id = data['leave_id']
        user = User.objects.filter(username=request.user).first()
        leave = Leave.objects.filter(id=leave_id).first()
        try:
            leave.status = '未通过'
            leave.save()
            return JsonResponse({'msg': 'OK', 'code': 200})
        except Exception as e:
            return JsonResponse({'msg': f'审批失败原因是{e}', 'code': 400})

    @staticmethod
    def get_need_examine_leave_list(leaves, role):
        examine_leave_list = []
        for i in leaves:
            if i.examine.all().values():
                agree_num = 0
                for k in list(i.examine.all().values()):
                    if k['is_agree']:
                        agree_num += 1
                if role == '班主任':
                    if agree_num == 0:
                        examine_leave_list.append(i)
                elif role == '老师':
                    if agree_num == 1:
                        examine_leave_list.append(i)
                elif role == '院长':
                    if agree_num == 2 and agree_num < len(list(i.examine.all().values())):
                        examine_leave_list.append(i)
                elif role == '校长':
                    if agree_num == 3 and agree_num < len(list(i.examine.all().values())):
                        examine_leave_list.append(i)
        return examine_leave_list


class TeacherAskLeave(View):
    @method_decorator(check_permission(['院长']))
    def get(self, request):
        dean = User.objects.filter(username=request.user).first()
        classes = College.objects.filter(college_dean=dean).first().colleges.all()
        need = [Role.objects.get(name='老师'), Role.objects.get(name='班主任')]
        all_user = [item for sublist in classes for item in sublist.user.all()]
        teacher_list = []
        for i in all_user:
            if any(item in i.roles.all() for item in need):
                teacher_list.append(i)
        leaves = Leave.objects.filter(Q(ask_user__in=teacher_list) & Q(status='审核中')).all().order_by('-ask_time')
        leave_list = [{'ask_user': i.ask_user.username, 'description': i.description, 'ask_time': i.ask_time,
                       'start_time': i.start_time, 'end_time': i.end_time, 'leave_id': i.id} for i in leaves]
        return JsonResponse({'msg': 'ok', 'code': 201, 'data': leave_list})

    """老师或班主任请假功能"""

    @method_decorator(check_permission(['老师', '班主任']))
    def post(self, request):
        data = json.loads(request.body)
        reason_id = data['reason_type']
        username = request.user
        user = User.objects.filter(username=username).first()
        try:
            leave_ = Leave.objects.filter(
                Q(ask_user=user) & Q(status='审核中')).first()
            if leave_:
                return JsonResponse({'msg': '您已经提交过请假申请，请耐心等待审核', 'code': 401})
        except:
            pass
        start_time = data['start_time']
        end_time = data['end_time']
        description = data['description']
        reason = ReasonType.objects.filter(id=reason_id).first()
        leave = Leave.objects.create(ask_user=user, reason_type=reason, description=description, start_time=start_time,
                                     end_time=end_time)
        dean = user.classes_user.first().colleges.college_dean
        leave.examine_user.add(dean)
        return JsonResponse({'msg': 'ok!!!', 'code': 201})

    # def put(self, request):

